package cn.clq.system.service.impl;

import cn.clq.system.domain.Menu;
import cn.clq.system.mapper.MenuMapper;
import cn.clq.system.service.IMenuService;
import cn.clq.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenlei
 * @since 2022-06-21
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> getMenuTree() {
        //1.查出所有菜单
        List<Menu> menus = menuMapper.loadAll();
        Map<Long, Menu> allMenu = menus.stream().collect(Collectors.toMap(Menu::getId, menu -> menu));
        //新建第一层级的list集合
        ArrayList<Menu> firstMenu = new ArrayList<>();
        //2.是顶级就新增到list
        for(Menu menu:menus){
            if(menu.getParentId()==null){
                firstMenu.add(menu);
            }else{
                //3.不是顶级就找自己的父亲
                Menu patentMenu = allMenu.get(menu.getParentId());
                    if(patentMenu!=null){
                        patentMenu.getChildren().add(menu);
                    }
            }
        }
        System.out.println(firstMenu);
        return firstMenu;
    }
}
